#!/bin/bash
#
#	Vamos iniciar 15 maquinas para trabalhar no algoritmo.
#	Para isso, temos uma hierarquia de conexao em arvore binaria com
#	uma raiz e 8 nos folhas.
#	Devemos determinar quais serao as maquinas para trabalhar no script abaixo.
#	Assim, temos:
#		ROOT		 - node1
#		SECOND LEVEL	 - node2,node3
#		THIRD LEVEL	 - node4,node5,node6,node7
#		LEAFS		 - node8,node9,node10,node11,node12,node15,node16,node17


ssh node1 "./root 3000 " &

# delay colocado entra cada camada
sleep 1
ssh node2 "./secondL 3100 3000 node1 " &
ssh node3 "./secondL 3110 3001 node1 " &

# delay segunda camada
sleep 1
ssh node4 "./thirdL 3200 3100 node2 " &
ssh node5 "./thirdL 3210 3101 node2 " &
ssh node6 "./thirdL 3220 3110 node3 " &
ssh node7 "./thirdL 3230 3111 node3 " &

# delay terceira camada
sleep 1
ssh node8 "./leaf 3200 node4 >leaf1.txt" &
ssh node9 "./leaf 3201 node4 >leaf2.txt" &
ssh node10 "./leaf 3210 node5 >leaf3.txt" &
ssh node11 "./leaf 3211 node5 >leaf4.txt" &
ssh node12 "./leaf 3220 node6 >leaf5.txt" &
ssh node15 "./leaf 3221 node6 >leaf6.txt" &
ssh node16 "./leaf 3230 node7 >leaf7.txt" &
ssh node17 "./leaf 3231 node7 >leaf8.txt" &

# concatenamos arquivos de output em um so
sleep 1.5 
cat leaf1.txt leaf2.txt leaf3.txt leaf4.txt leaf5.txt leaf6.txt leaf7.txt leaf8.txt > result.txt

# excluindo arquivos de output
rm leaf1.txt 
rm leaf2.txt
rm leaf3.txt
rm leaf4.txt
rm leaf5.txt
rm leaf6.txt
rm leaf7.txt
rm leaf8.txt

# saindo do Shell
exit
